package com.xuqm.base.common;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ToolsHelper {

    public static boolean isNull(Object obj) {
        if (null == obj)
            return true;
        String str = obj.toString();
        if (str.isEmpty())
            return true;
        return str.equalsIgnoreCase("null");
    }

    public static Long toLong(Object obj) {
        if (isNull(obj))
            return 0L;
        try {
            return Long.parseLong(obj.toString());
        } catch (Exception e) {
            return 0L;
        }
    }
    public static Double toDouble(Object obj) {
        if (isNull(obj))
            return 0.0;
        try {
            return Double.parseDouble(obj.toString());
        } catch (Exception e) {
            return 0D;
        }
    }

    public static String toString(Object obj) {
        if (isNull(obj))
            return "";
        return obj.toString();
    }


    /**
     * 格式化json字符串
     *
     * @param jsonStr 需要格式化的json串
     * @return 格式化后的json串
     */
    public static String formatJson(String jsonStr) {
        if (null == jsonStr || "".equals(jsonStr)) return "";
        StringBuilder sb = new StringBuilder();
        char last = '\0';
        char current = '\0';
        int indent = 0;
        for (int i = 0; i < jsonStr.length(); i++) {
            last = current;
            current = jsonStr.charAt(i);
            //遇到{ [换行，且下一行缩进
            switch (current) {
                case '{':
                case '[':
                    sb.append(current);
                    sb.append('\n');
                    indent++;
                    addIndentBlank(sb, indent);
                    break;
                //遇到} ]换行，当前行缩进
                case '}':
                case ']':
                    sb.append('\n');
                    indent--;
                    addIndentBlank(sb, indent);
                    sb.append(current);
                    break;
                //遇到,换行
                case ',':
                    sb.append(current);
                    if (last != '\\') {
                        sb.append('\n');
                        addIndentBlank(sb, indent);
                    }
                    break;
                default:
                    sb.append(current);
            }
        }
        return sb.toString();
    }

    /**
     * 添加space
     */
    private static void addIndentBlank(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append('\t');
        }
    }

    /**
     * http 请求数据返回 json 中中文字符为 unicode 编码转汉字转码
     *
     * @param theString
     * @return 转化后的结果.
     */
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuilder outBuffer = new StringBuilder(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }

                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't') {
                        aChar = '\t';
                    } else if (aChar != 'r') {
                        if (aChar == 'n') {
                            aChar = '\n';
                        } else if (aChar == 'f') {
                            aChar = '\f';
                        }
                    } else {
                        aChar = '\r';
                    }
                    outBuffer.append(aChar);
                }
            } else {
                outBuffer.append(aChar);
            }
        }
        return outBuffer.toString();
    }

    /**
     * 弹出提示信息  感觉比Toast好看点  不过Toast不需要依赖view
     *
     * @param view    绑定一个view才能展示
     * @param content 需要展示的内容
     */
    public static void snack(View view, CharSequence content) {
        Snackbar.make(view, content, Snackbar.LENGTH_SHORT).show();
    }

    public static void showMessage(CharSequence content) {
        Toast.makeText(AppManager.getInstance().getActivity(), content, Toast.LENGTH_SHORT).show();
    }

    /**
     * EditText绑定TextInputLayout，处理一下
     *
     * @param editText        editText
     * @param textInputLayout textInputLayout
     */
    public static void addTextChangedListener(EditText editText, TextInputLayout textInputLayout) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(textInputLayout.getError())) {//输入的时候不提示错误信息
                    textInputLayout.setErrorEnabled(true);
                    textInputLayout.setError("");
                    textInputLayout.setErrorEnabled(false);
                }
            }
        });
    }

    /**
     * 使用 TextInputLayout  提示错误信息
     *
     * @param textInputLayout TextInputLayout
     * @param msg             错判的内容
     */
    public static void showError(TextInputLayout textInputLayout, String msg) {
        textInputLayout.setErrorEnabled(true);
        textInputLayout.setError(msg);
    }

    /**
     * 将Object对象里面的属性和值转化成Map对象
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static <T> Map<String, T> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, T> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            T value = (T) field.get(obj);
            if (null != value)
                map.put(fieldName, value);
        }
        return map;
    }
}
